// pages/login/login.js

const app = getApp();
var ctx;
import { hexMD5, b64MD5 } from '../../utils/md5.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    color: 0,
    loadingHidden: true,
    username: '', //学号
    studentPassword: '', //密码
    loginCode: '',
    text: '', //验证码文字
    securityCode: '', //验证码
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    drawPic(that); //验证码
    console.log("opt", options);
    // 登录
    wx.login({
      success: function (res) {
        // console.log(res);
        if (res.code) {
          that.setData({
            loginCode: res.code
          })
          // console.log('获取code', that.data.loginCode);
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    });
  },

  //用户名、密码 验证码
  bindChange: function (e) {
    var val = e.detail.value;
    // console.log("e",e);
    switch (e.target.id) {
      case "username":
        this.setData({
          username: val
        });
        break;
      case "studentPassword":
        this.setData({
          studentPassword: val
        });
        break;
      case "securityCode":
        this.setData({
          securityCode: val
        });
        break;
    }
  },

  bindGetUserInfo: function (e) {
    let _this = this
    console.log('您的学号：', hexMD5(_this.data.username))
    console.log('您的密码：', b64MD5(_this.data.studentPassword))
    console.log('您的微信码：', _this.data.loginCode)
    console.log('您的验证码：', _this.data.securityCode)
    if (_this.data.securityCode != '') {
      var myimgCode = _this.data.securityCode.toUpperCase();
      if (_this.data.text !== myimgCode) {
        wx.showModal({
          content: "验证码错误",
          showCancel: false,
        })
        this.imgCodeChange()
      } else {
        this.goBingding();
      }
      console.log("90", myimgCode);
    } else {
      wx.showModal({
        content: "请输入验证码",
        showCancel: false,
      })
      this.imgCodeChange()
    }

  },
  goBingding() {
    let mypassword = b64MD5(this.data.studentPassword)
    console.log("加密", mypassword);
    console.log("code111", this.data.loginCode);
    wx.request({
      url: app.api.binding,
      method: 'POST',
      data: {
        username: this.data.username,
        password: this.data.studentPassword,
        // username: '03021240',
        // password: '1',
        weChatCode: this.data.loginCode,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      success: (res) => {
        console.log("000111", res)
        if (res.data.code == 0) {
          console.log("绑定", res.data.data.token);
          wx.setStorageSync('token', res.data.data.token);
          wx.reLaunch({
            url: '/pages/index/index',
          })
        } else if (res.data.code == 16) {
          this.getUserToken()
        } else {
          wx.reLaunch({
            url: '/pages/login/login',
          })
        }

      }
    })
  },
  getUserToken() {
    wx.login({
      success: function (res) {
        console.log(res);
        if (res.code) {
          // 换取koken
          console.log('获取code', res.code);
          wx.request({
            url: app.api.getUserToken,
            data: { code: res.code },
            header: {
              'content-type': 'application/x-www-form-urlencoded'  // 默认值
            },
            method: "POST",
            success: (res) => {
              console.log('login返回', res.data);
              var value = res.data.data;
              // console.log('login返回', value);

              console.log('这是login的token' + value.token);
              wx.setStorageSync('token', value.token);
              var token = wx.getStorageSync('token');
              console.log("8787", token);
              wx.reLaunch({
                url: '/pages/index/index',
              })

            }, fail: function (res) {
              console.log('最外面的失败吧')
              that.data.text_value + 'outer_fail' + res + "\n";
            }
          })
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    });
  },
  /// 图形验证码
  imgCodeChange: function () {
    // console.log("22");
    var that = this;
    drawPic(that);
    that.setData({
      securityCode: '',
    })
  },
  mobile(e) {
    this.setData({
      mobile: e.detail.value
    })
  },


})
function randomNum(min, max) {
  return Math.floor(Math.random() * (max - min) + min);
}
/**生成一个随机色**/
function randomColor(min, max) {
  var r = randomNum(min, max);
  var g = randomNum(min, max);
  var b = randomNum(min, max);
  return "rgb(" + r + "," + g + "," + b + ")";
}

/**绘制验证码图片**/
function drawPic(that) {
  ctx = wx.createCanvasContext('canvas');
  /**绘制背景色**/
  ctx.fillStyle = randomColor(180, 240); //颜色若太深可能导致看不清
  ctx.fillRect(0, 0, 160, 56)
  /**绘制文字**/
  var arr;
  var text = '';
  var str = 'ABCEFGHJKLMNPQRSTWXY123456789';
  for (var i = 0; i < 4; i++) {
    var txt = str[randomNum(0, str.length)];
    ctx.fillStyle = randomColor(50, 160); //随机生成字体颜色
    ctx.font = randomNum(26, 30) + 'px SimHei'; //随机生成字体大小
    var x = 5 + i * 20;
    var y = randomNum(20, 25);
    var deg = randomNum(-20, 20);
    //修改坐标原点和旋转角度
    ctx.translate(x, y);
    ctx.rotate(deg * Math.PI / 180);
    ctx.fillText(txt, 5, 0);
    text = text + txt;
    //恢复坐标原点和旋转角度
    ctx.rotate(-deg * Math.PI / 180);
    ctx.translate(-x, -y);
  }
  /**绘制干扰线**/
  for (var i = 0; i < 4; i++) {
    ctx.strokeStyle = randomColor(40, 180);
    ctx.beginPath();
    ctx.moveTo(randomNum(0, 90), randomNum(0, 28));
    ctx.lineTo(randomNum(0, 90), randomNum(0, 28));
    ctx.stroke();
  }
  /**绘制干扰点**/
  for (var i = 0; i < 20; i++) {
    ctx.fillStyle = randomColor(0, 255);
    ctx.beginPath();
    ctx.arc(randomNum(0, 90), randomNum(0, 28), 1, 0, 2 * Math.PI);
    ctx.fill();
  }
  ctx.draw(false, function () {
    that.setData({
      text: text
    })
  });
}